<template>
  <BaseOperateTable
    ref="refPage"
    :show-selection="true"
    :header="columns"
    :button-list="{}"
    :query-url="queryUrl"
    :delete-url="deleteUrl"
    :data-filter="tabelDataFilter"
    @operate="tableOperate"
    @query="query"
    @deleted="onRowsDeleted"
    @reset="resetCondition">
    <template v-slot:condition>
      <div>创建时间：
        <a-range-picker
          v-model:value="createTimeRange"
          style="width:200px"
          format="YYYY-MM-DD"
          @change="onCreateTimeRangeChange" />
      </div>
      <div>路口名称：
        <a-input
          v-model:value="condition.name"
          :allow-clear="true"
          placeholder="请输入路口名称"/>
      </div>
    </template>
    <template v-slot:operate>
      <a-button
        type="primary"
        @click="addData">添加数据</a-button>
      <a-button
        type="primary"
        danger
        @click="batchDelete">删除数据</a-button>
    </template>
    <template v-slot:action="{record}">
      <a-button
        type="link"
        :disabled="record.lstatus === 1"
        @click="tableOperate({eventType:'online',data: record})">上线</a-button>
      <a-button
        type="link"
        :disabled="record.lstatus !== 1"
        @click="tableOperate({eventType:'offline',data: record})">下线</a-button>
      <a-button
        type="link"
        danger
        :disabled="record.lstatus === 1"
        @click="tableOperate({eventType:'delete',data: record})">删除</a-button>
    </template>
  </BaseOperateTable>
   <ImportDialog
    v-if="importDialogVisible"
    v-model:visible="importDialogVisible"
    :import-url="importUrl"
    @onSuccess="onImportFileSuccess"/>
</template>
<script setup>
import { ref, reactive } from 'vue'
import { message } from 'ant-design-vue'
import { trafficLightOnline, trafficLightOffline } from '@/api/signal/signal'
import {CarStatusList as StuatusList} from '@/config/simulation'
import BaseOperateTable from '@/components/BaseOperateTable.vue'
import ImportDialog from './ImportDialog.vue'
import { BasePath } from '@/api/request'

const refPage = ref(null) // 表格实例
const importDialogVisible = ref(false) // 导入弹窗显隐

/** ========== Table ========== */
const queryUrl = ref(`${BasePath}/trafficlightsConfig/page`) // 分页查询接口URL
const deleteUrl = ref(`${BasePath}/trafficlightsConfig/`) // 批量删除接口URL
const importUrl = ref(`${BasePath}/trafficlightsConfig`)
/** 表格标题栏配置 */
const columns = ref([
  {
    title: '路口名称',
    dataIndex: 'name',
    width: 200,
    ellipsis: true
  },
  {
    title: '信号灯编号',
    dataIndex: 'lightIdsStr',
    width: 320,
    ellipsis: true
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 160,
    ellipsis: true
  },
 {
    title: '状态',
    dataIndex: 'lstatusLabel',
    width: 100,
    ellipsis: true
  },
  {
    title: '操作人',
    dataIndex: 'updateBy',
    width: 100,
    ellipsis: true
  },
  {
    title: '操作',
    dataIndex: 'xxx',
    fixed: "right",
    width: 260,
    slots: { customRender: 'action' }
  }
])

/** 表格数据过滤 */
const tabelDataFilter = (rows) => {
  const result = []
  rows.forEach((item) => {
    let i = { ...item }
    i.lightIdsStr = (item.lightIds || []).join(',')
    i.lstatusLabel = StuatusList[i.lstatus || 0].label;
    result.push(i)
  })
  return result
}

/** 表格操作列事件 */
const tableOperate = ({ eventType, data }) => {
  if (eventType === 'online') {
    // 上线
    trafficLightOnline(data.id).then(() => {
      message.success('上线成功')
      refPage.value.query()
    })
  } else if (eventType === 'offline') {
    // 下线
    trafficLightOffline(data.id).then(() => {
      message.success('下线成功')
      refPage.value.query()
    })
  } else {
    // 删除车辆关联关系
    refPage.value.deleteRow(data.id)
  }
}
/** 数据删除成功事件 */
const onRowsDeleted = () =>{
  refPage.value.query()
}
/** ========== Condition ========== */
const createTimeRange = ref([])
// 查询条件
const condition = reactive({
  name: undefined,
  startTime: undefined,
  endTime: undefined
})

/** 重置条件 */
const resetCondition = () => {
  condition.name = undefined
  condition.startTime = undefined
  condition.endTime = undefined
  createTimeRange.value = []
}

/** 点击查询按钮后，进行表格查询 */
const query = () => {
  refPage.value.queryByCondition(condition, true)
}

/** 创建时间改变事件 */
const onCreateTimeRangeChange = (v1, v2) => {
  if (v2.length === 2) {
    let[startTime, endTime] = v2
    condition.startTime = v1.length?(startTime + ' 00:00:00') : undefined
    condition.endTime =  v1.length?(endTime + ' 23:59:59') : undefined
  }
}

/** ========= Operate ========== */
/** 添加数据 */

const addData = () => {
  importDialogVisible.value = true
}

const onImportFileSuccess = () => {
  importDialogVisible.value = false
  resetCondition()
  refPage.value.resetQuery()
}

/** 批量删除 */
const batchDelete = () => {
  const selectedRows = refPage.value.getSelectedRows()
  const onlineRows =selectedRows.filter(({lstatus}) => lstatus === 1)
  if(onlineRows.length > 0){
    message.warning('请先下线模拟')
    return
  }
  refPage.value.deleteSelectedRows()
}

</script>
<script>
export default {
  name: 'signalLight'
}
</script>